<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <link rel="stylesheet" href="https://smohan.oss-cn-beijing.aliyuncs.com/static/demos/styles/file-rw-in-browser.css">

  <div class="file-reader">
    <div class="form">
      <label class="uploader">
        <input type="file" id="file">
        <span class="btn" role="button">选择文件</span>
      </label>
      <div class="actions">
        <button class="btn" id="readFile" disabled>读取文件</button>
      </div>
    </div>
    <div class="infos" id="infos">
      <p style="color: #999;">请选择文本类型文件</p>
    </div>
    <div class="content">
      <textarea id="content" placeholder="文件内容..."></textarea>
    </div>
  </div>
</body>
<script>
  const $ = id => document.getElementById(id)
  const $file = $('file')
  const $content = $('content')
  const $readBtn = $('readFile')
  const $infos = $('infos')

  const fileReader = new FileReader()

  // 保存当前文件域引用
  let currentFile = null

  const readFile = () => {
    if (!currentFile) {
      alert('请选择文件')
      return
    }
    fileReader.onloadend = function (evt) {
      // 在文件读取完毕后，其内容将被保存在result属性中
      const content = evt.target.result
      $content.focus()
      $content.value = content
    }
    // 以utf-8编码文本格式来读取
    fileReader.readAsDataURL(currentFile, 'utf-8')
  }

  const setInfos = file => {
    const html = `
      <ul>
        <li>文件名称：${file.name}</li>
        <li>文件大小：${file.size} Bytes</li>
      </ul>
    `
    $infos.innerHTML = html
  }

  $file.onchange = evt => {
    const file = evt.target.files[0]
    setInfos(file)
    currentFile = file
    evt.value = null
    $readBtn.removeAttribute('disabled')
  }

  $readBtn.addEventListener('click', () => readFile())
</script>



</html>